package com.lin.exceptionHandler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

//@Component
public class CustomExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 返回一个错误视图
        /*ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/static/error2.html");*/

        // 回写Json字符串
        response.setContentType("application/json;charset=utf-8");
        String resJSon = "{\"code\":500,\"msg\":\"服务器异常，请稍后再试\"}";
        try {
            response.getWriter().write(resJSon);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
